import React, { useEffect, useRef } from 'react';
import { Table, Button, Image, Space, Divider, Modal, message } from 'antd';
import { observer } from 'mobx-react';
import classify from '../../mobx/classify';
import ClassifyModal from './ClassifyModal';

function ClassifyIndex() {

  const modalRef = useRef(null);

  const edit = (row) => {
    const { id, pid, name, cover } = row;
    // 将待编辑的类目数据传递给模态框组件
    modalRef.current.getClassifyData({ id, pid, name, cover });
  }

  const del = (id) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除?',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        const res = await classify.remvoeClassify(id);
        if (res.code !== 200) {
          message.error(res.msg);
        }
      }
    });
  }

  // 表格配置
  const columns = [
    {
      title: '序号',
      dataIndex: 'id'
    },
    {
      title: '名称',
      dataIndex: 'name'
    },
    {
      title: '封面图',
      render: (row) => {
        return row.cover && <Image src={row.cover} width={100} />
      }
    },
    {
      title: '操作',
      render: (row) => {
        if (row.id > 0) {
          return <Space>
            <Button onClick={() => edit(row)} type="primary">编辑</Button>
            <Button onClick={() => del(row.id)} type="primary" danger>删除</Button>
          </Space>
        }
      }
    }
  ];


  useEffect(() => {
    // 请求类目列表数据
    classify.getClassifyList();
  }, []);

  const toggleModal = () => {
    // 显示对话框组件
    modalRef.current.toggleModal();
  }

  return (
    <div className='table-container'>
      <h1>类目管理</h1>
      <Button className='btn-add' type='primary' onClick={toggleModal}>新增</Button>
      <Divider></Divider>
      <Table rowKey='id' pagination={false} columns={columns} dataSource={classify.classifyList}></Table>
      {/* 对话框组件  */}
      <ClassifyModal ref={modalRef} />
    </div>
  )
}
export default observer(ClassifyIndex);
